import axios from "axios";

const myaxios = axios.create({
  baseURL: 'http://101.42.252.241:8080',
  timeout: 100000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加请求拦截器
myaxios.interceptors.request.use(function (config) {
  // 在发送请求之前附加授权头
  try {
    const rawToken = (typeof window !== 'undefined')
      ? (localStorage.getItem('token') || sessionStorage.getItem('token') || localStorage.getItem('authToken') || '')
      : ''
    if (rawToken) {
      const token = rawToken.startsWith('Bearer ') ? rawToken : `Bearer ${rawToken}`
      config.headers = config.headers || {}
        ; (config.headers as any)['Authorization'] = token
    }
  } catch { }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});
// 添加响应拦截器
myaxios.interceptors.response.use(function (response) {
  // 2xx 范围内的状态码都会触发该函数。
  // 解析服务端返回的 Authorization，自动持久化 token
  try {
    let saved = false
    const authHeader = (response.headers?.['authorization'] || response.headers?.['Authorization']) as string | undefined
    if (authHeader && typeof window !== 'undefined') {
      const bearer = authHeader.startsWith('Bearer ') ? authHeader : `Bearer ${authHeader}`
      const raw = bearer.replace(/^Bearer\s+/i, '')
      localStorage.setItem('authToken', bearer)
      localStorage.setItem('token', raw)
      myaxios.defaults.headers.common['Authorization'] = `Bearer ${raw}`
      saved = true
    }
    // 同时支持后端将 token 放在响应体
    const d: any = response?.data
    const bodyToken = d?.token || d?.accessToken || d?.Authorization || d?.authorization || d?.data?.token || d?.data?.accessToken
    if (!saved && bodyToken && typeof window !== 'undefined') {
      const bearer = String(bodyToken).startsWith('Bearer ') ? String(bodyToken) : `Bearer ${String(bodyToken)}`
      const raw = String(bearer).replace(/^Bearer\s+/i, '')
      localStorage.setItem('authToken', bearer)
      localStorage.setItem('token', raw)
      myaxios.defaults.headers.common['Authorization'] = `Bearer ${raw}`
    }
  } catch { }
  return response;
}, function (error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 401 处理：清理本地 token，必要时可跳转登录
  try {
    const status = error?.response?.status
    if (status === 401 && typeof window !== 'undefined') {
      localStorage.removeItem('token')
      localStorage.removeItem('authToken')
      sessionStorage.removeItem('token')
      // 可按需跳转到登录页：
      //window.location.href = '/'
    }
  } catch { }
  return Promise.reject(error);
});

export default myaxios